<script setup lang="ts">
import { ref, watch } from 'vue'
import allArea from './lib/pca-code.json'

type palceItem = {
  code: string,
  name: string,
  children?: palceItem[]
}

const emits = defineEmits(['change'])

const areas = ref(allArea)
const province = ref('')
const city = ref('')
const area = ref('')
const cityOptions = ref<palceItem[]>([])
const areaOptions = ref<palceItem[]>([])

watch(() => province.value, (val) => {
  if(val) {
    cityOptions.value = areas.value.find(item => item.code=== province.value)!.children
  } else {
    cityOptions.value = []
  }
  city.value = ''
  area.value = ''
})

watch(() => city.value, (val) => {
  if(val) {
    areaOptions.value = cityOptions.value.find(item => item.code === city.value)!.children!
  } else {
    areaOptions.value = []
  }
})

type Data = {
  name: string,
  code: string
}

watch(() => area.value, val => {
  if (val) {
    let provinceData: Data = {
      code: province.value,
      name: province.value && areas.value.find(item => item.code === province.value)!.name!
    }
    let cityData: Data = {
      code: city.value,
      name: city.value && cityOptions.value.find(item => item.code === city.value)!.name!
    }
    let areaData: Data = {
      code: area.value,
      name: area.value && areaOptions.value.find(item => item.code === area.value)!.name!
    }
    emits('change', {
      province: provinceData,
      city: cityData,
      area: areaData,
    })
  }
})

</script>

<template>
  <div class="area-page">
    <el-select placeholder="请选择省份" v-model="province">
      <el-option v-for="item in areas" :key="item.code" :value="item.code" :label="item.name">
        {{ item.name }}
      </el-option>
    </el-select>
    <el-select :disabled="!province" placeholder="请选择省市" v-model="city">
      <el-option v-for="item in cityOptions" :key="item.code" :value="item.code" :label="item.name">
        {{ item.name }}
      </el-option>
    </el-select>
    <el-select :disabled="!city || !province" placeholder="请选择区域" v-model="area">
      <el-option v-for="item in areaOptions" :key="item.code" :value="item.code" :label="item.name">
        {{ item.name }}
      </el-option>
    </el-select>
  </div>
</template>

<style lang="scss" scoped>
.area-page {
  display: flex;
  column-gap: 20px;
}
</style>

